<?php
/**
 * 优惠券操作功能
 * @package  htdocs
 * @subpackage  quanliadmin
 */

//引入优惠券类
quanli_require('module/base/promotion/quanliCoupon.class.php');

//引入部门类
quanli_require('module/base/system/sysDepartment.class.php');

class pa_coupon {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && is_numeric($_REQUEST['operFlg'])) {

            switch ($_REQUEST['operFlg']) {

                case 1: //优惠券列表信息
                    $this->couponList();
                    break;

                case 2: //新增/编辑优惠券
                    $this->editCoupon( $_REQUEST['operFlg'] );
                    break;

                case 4: //查看优惠券
                    $this->couponCodeList();
                    break;
                case 5:     //发放优惠券
                    $this->issueAccountCoupon();
                    break;
                case 6:     //导入优惠券
                    $this->importCoupon();
                    break;

                case 7:     //导出优惠券
                    $this->exportCoupon();
                    break;

                case 8:     //大批量导入优惠券
                    $this->bigImportCoupon();
                    break;
                //add by 2014-10-29 yim.hu FUN-BK-0010 优惠券重置显示页面 start
                case 9:     //优惠券重置显示页面
                	$this->resetCoupon();
                    break;
                //add by 2014-10-29 yim.hu FUN-BK-0010 优惠券重置显示页面 end
                default:
                    $this->toError('参数错误');
                    break;
            }

        } else {

            $this->toError('参数错误');

        }




    }

    private function toError( $msg ) {

        global $G_PGLOB;

        $G_PGLOB->display_error_page( $msg );

    }

    /**
     * 优惠券列表信息
     */
    private function couponList() {

        global $G_PGLOB;

        $G_PGLOB->smarty->display('promotion/coupon_list.tpl');

    }

    /**
     * 新增或修改优惠券
     */
    private function editCoupon() {

        global $G_PGLOB;

        //实例部门类
        $sysDepartment = new sysDepartment();

        //部门数据
        $department_array = array();

        //递归查询部门数据
        $sysDepartment->searchDepartment( $department_array );

        //生成下拉框html代码
        $department_select_html = '';
        $sysDepartment->createDepartmentSelectOptionHtml( $department_array, $department_select_html );

        $G_PGLOB->smarty->assign('department_select_html', $department_select_html);

        quanli_require('module/base/promotion/promotionHandler.class.php');

        //促销类
        $promotionHandler = new promotionHandler( $G_PGLOB->DBCA ) ;

        //获取商品筛选规则
        $result_goods_select = $promotionHandler->goodsSelectorList( $_REQUEST ) ;
        $G_PGLOB->smarty->assign_by_ref('goods_select', $result_goods_select);

        //获取用户筛选器
        $result_user_select = $promotionHandler->userSelectorList( $_REQUEST );
        $G_PGLOB->smarty->assign_by_ref('user_select', $result_user_select);

        if (isset($_REQUEST['couponID']) && is_numeric($_REQUEST['couponID'])) {

            //实例化优惠券类
            $quanliCoupon = new quanliCoupon($G_PGLOB->DBCA);

            //查询
            $arg_array = array(
                'couponID' => $_REQUEST['couponID']
            );
            $coupon_array = $quanliCoupon->searchCoupon( $arg_array );

            if (!$coupon_array) {
                $this->toError('优惠券信息没有找到');
            }

            //查询优惠券对应的城市
            $coupon_city_array = $quanliCoupon->searchCouponCity( $arg_array );

            $coupon_array[0]['cityID'] = array(); //城市ID数组
            if( $coupon_city_array ){
                foreach( $coupon_city_array as $val ){
                    array_push( $coupon_array[0]['cityID'],$val['cityID']);
                }
            }

            $G_PGLOB->smarty->assign_by_ref('coupon_array', $coupon_array[0]);

        } else {

            $G_PGLOB->smarty->assign('startDate', $G_PGLOB->sys_date);
            $G_PGLOB->smarty->assign('endDate', $G_PGLOB->sys_date);

        }

        //查询城市信息
        $city_array = get_city();
        $G_PGLOB->smarty->assign_by_ref('city_array', $city_array);

        $G_PGLOB->smarty->display('promotion/couponEdit.tpl');

    }

    /**
     * 查看优惠券编号
     */
    private function couponCodeList(){

        global $G_PGLOB;

        if(!isset($_REQUEST['id']) || !is_numeric(trim($_REQUEST['id'])) ){
            $this->toError('参数错误');
        }

        $G_PGLOB->smarty->assign('couponID', trim($_REQUEST['id']));
        $G_PGLOB->smarty->display('promotion/coupon_code_list.tpl');


    }

    /**
     * 发放优惠券
     */
    private function issueAccountCoupon() {

        global $G_PGLOB;

        if(!isset($_REQUEST['couponID']) || !is_numeric(trim($_REQUEST['couponID'])) ){
            $this->toError('参数错误');
        }

        $G_PGLOB->smarty->assign('couponID', trim($_REQUEST['couponID']));
        $G_PGLOB->smarty->display('promotion/issueCoupon.tpl');

    }


    /**
     * 导入优惠券
     */
    private function importCoupon() {

        global $G_PGLOB;

        error_log('优惠券导入开始时间：' . $G_PGLOB->sys_datetime);

        if(!isset($_REQUEST['couponID']) || !is_numeric($_REQUEST['couponID'])) {
            die("<script>parent.coupon.importMsg('参数错误',0);</script>");
        }

        //检查上传的文件
        switch ($_FILES['search_file']['error']) {

            case 1:
                // 文件大小超出了服务器的空间大小
                echo "<script>parent.E.loadding.close();parent.E.alert('文件过大，请重新上传');</script>";
                return;
                break;

            case 2:
                // 要上传的文件大小超出浏览器限制
                echo "<script>parent.E.loadding.close();parent.E.alert('文件过大，请重新上传');</script>";
                return;
                break;

            case 3:
                // 文件仅部分被上传
                echo "<script>parent.E.loadding.close();parent.E.alert('文件上传有误，请重新上传');</script>";
                return;
                break;

            case 4:
                // 没有找到要上传的文件
                echo "<script>parent.E.loadding.close();parent.E.alert('请选择上传的文件');</script>";
                return;
                break;

            case 5:
                // 服务器临时文件夹丢失
                echo "<script>parent.E.loadding.close();parent.E.alert('系统错误，上传失败');</script>";
                return;
                break;

            case 6:
                // 文件写入到临时文件夹出错
                echo "<script>parent.E.loadding.close();parent.E.alert('系统错误，上传失败');</script>";
                return;
                break;
        }

        //上传路径
        $upload_path = 'quanliadmin/docroot/images/temp/message/';

        //分解文件名和扩展名
        $fileArray = explode('.', $_FILES['search_file']['name']);
        $index = count($fileArray) - 1;

        //将扩展名转化成小写
        $extension = strtolower($fileArray[$index]);


        //检查格式是否正确
        if ($extension != 'xlsx' && $extension != 'csv' && $extension != 'xls' ) {
            echo "<script>parent.E.loadding.close();parent.E.alert('文件格式有误');</script>";
            return;
        }

        //检查文件夹
        if (!file_exists(G_APPLICATION_BASEPATH . $upload_path)) {
            mkdir(G_APPLICATION_BASEPATH . $upload_path, 0777, true);
        }

        //获取UUID
        $guid = make_uuid();

        //文件名
        $moveFile = $upload_path . $guid . '.' . $extension;
        if (!move_uploaded_file($_FILES['search_file']['tmp_name'], G_APPLICATION_BASEPATH . $moveFile)) {
            echo "<script>parent.E.loadding.close();parent.E.alert('系统错误，上传失败');</script>";
            return;
        }


        //读取文件
        $excelData = file(G_APPLICATION_BASEPATH . $moveFile);
        if (!isset($excelData[0])) {
            echo "<script>parent.E.loadding.close();parent.E.alert('导入数据为空');</script>";
            return;
        }
        error_log('读取优惠券数据完成时间：' . $G_PGLOB->sys_datetime);
        error_log('优惠券总数量：' . count($excelData));


        /**
         * ======================================
         * 发放优惠券
         * ======================================
         */

        //实例化优惠券类
        $quanliCoupon = new quanliCoupon( $G_PGLOB->DBCA );
        $result_array = $quanliCoupon->createCouponCode($_REQUEST['couponID'], $excelData, false,$G_PGLOB->currentUserID);
        error_log('优惠券导入完成时间：' . $G_PGLOB->sys_datetime);
        if ($result_array['code'] != 200) {
            die("<script>parent.coupon.importMsg('" . $result_array['message'] . "',0);</script>");
        } else {
            die("<script>parent.coupon.importMsg('导入成功',0);</script>");
        }



        /**
         * ======================================
         * 发放优惠券
         * ======================================
         */

    }

    /**
     * 导出编号优惠券
     */
    function exportCoupon(){

        global $G_PGLOB;

        //检查phpexcel类
        quanli_include('framework/phpExecl/PHPExcel.php');
        quanli_include('framework/phpExecl/PHPExcel/Writer/Excel2007.php');

        //实例excel类
        $objPHPExcel = new PHPExcel();

        /**
         * 设置excel的属性
         */
        //创建人
        $objPHPExcel->getProperties()->setCreator("$G_PGLOB->currentUserName");
        //最后修改人
        $objPHPExcel->getProperties()->setLastModifiedBy("$G_PGLOB->currentUserName");
        //标题
        $objPHPExcel->getProperties()->setTitle("导出编号优惠券");
        //题目
        $objPHPExcel->getProperties()->setSubject("导出编号优惠券");
        //描述
        $objPHPExcel->getProperties()->setDescription("导出编号优惠券");
        /**
         * 设置excel的属性
         */

        /**
         * sheet
         */
        //设置当前的sheet
        $objPHPExcel->setActiveSheetIndex(0);
        //设置sheet的name
        $objPHPExcel->getActiveSheet()->setTitle('导出编号优惠券');
        /**
         * sheet
         */

        //实例化优惠券类
        $quanliCoupon = new quanliCoupon( $G_PGLOB->DBCA );

        //查询优惠券信息
        if( isset($_REQUEST['page']) && is_numeric($_REQUEST['page']) ){
            $_REQUEST['rp'] = 5000;
        }

        //查询
        $coupon_code_array = $quanliCoupon->searchCouponCode( $_REQUEST );

        /**
         * 设置标题
         */
        $objPHPExcel->getActiveSheet()->setCellValue('A1', '优惠券编码');
        $objPHPExcel->getActiveSheet()->setCellValue('B1', '优惠券金额');
        $objPHPExcel->getActiveSheet()->setCellValue('C1', '礼品券使用限额');
        $objPHPExcel->getActiveSheet()->setCellValue('D1', '截止日期');
        $objPHPExcel->getActiveSheet()->setCellValue('E1', '优惠券使用类型');
        /**
         * 设置标题
         */

        /**
         * 添加数据
         */
        if ($coupon_code_array) {

            $i = 2;

            foreach($coupon_code_array as &$Info) {

                if($Info['useType'] == 1){
                    $use_type = '券';
                }else{
                    $use_type = '红包';
                }

                $objPHPExcel->getActiveSheet()->setCellValue('A' . $i, $Info['code']);
                $objPHPExcel->getActiveSheet()->setCellValue('B' . $i, $Info['amount']);
                $objPHPExcel->getActiveSheet()->setCellValue('C' . $i, $Info['limitMoney']);
                $objPHPExcel->getActiveSheet()->setCellValue('D' . $i, $Info['endDate']);
                $objPHPExcel->getActiveSheet()->setCellValue('E' . $i, $use_type);

                $i++;

            }

        }
        /**
         * 添加数据
         */

        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);


        //文件名称
        $fileName = '导出编号优惠券_' . date('YmdHis') . '.xlsx';

        $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
        header("Content-Type: application/force-download");
        header("Content-Disposition:inline;filename=$fileName");
        header("Content-Transfer-Encoding: binary");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");
        $objWriter->save('php://output');

    }


    /**
     * 大批量导入优惠券
     */
    private function bigImportCoupon() {

        global $G_PGLOB;

        if(!isset($_REQUEST['couponID']) || !is_numeric($_REQUEST['couponID'])) {
            die("<script>parent.coupon.importMsg('参数错误',0);</script>");
        }

        //检查上传的文件
        switch ($_FILES['bigSearch_file']['error']) {

            case 1:
                // 文件大小超出了服务器的空间大小
                echo "<script>parent.E.loadding.close();parent.E.alert('文件过大，请重新上传');</script>";
                return;
                break;

            case 2:
                // 要上传的文件大小超出浏览器限制
                echo "<script>parent.E.loadding.close();parent.E.alert('文件过大，请重新上传');</script>";
                return;
                break;

            case 3:
                // 文件仅部分被上传
                echo "<script>parent.E.loadding.close();parent.E.alert('文件上传有误，请重新上传');</script>";
                return;
                break;

            case 4:
                // 没有找到要上传的文件
                echo "<script>parent.E.loadding.close();parent.E.alert('请选择上传的文件');</script>";
                return;
                break;

            case 5:
                // 服务器临时文件夹丢失
                echo "<script>parent.E.loadding.close();parent.E.alert('系统错误，上传失败');</script>";
                return;
                break;

            case 6:
                // 文件写入到临时文件夹出错
                echo "<script>parent.E.loadding.close();parent.E.alert('系统错误，上传失败');</script>";
                return;
                break;
        }

        //上传路径
        $upload_path = 'quanliadmin/docroot/images/temp/message/';

        //分解文件名和扩展名
        $fileArray = explode('.', $_FILES['bigSearch_file']['name']);
        $index = count($fileArray) - 1;

        //将扩展名转化成小写
        $extension = strtolower($fileArray[$index]);


        //检查格式是否正确
        if ($extension != 'xlsx' && $extension != 'csv' && $extension != 'xls' ) {
            echo "<script>parent.E.loadding.close();parent.E.alert('文件格式有误');</script>";
            return;
        }

        //检查文件夹
        if (!file_exists(G_APPLICATION_BASEPATH . $upload_path)) {
            mkdir(G_APPLICATION_BASEPATH . $upload_path, 0777, true);
        }

        //获取UUID
        $guid = make_uuid();

        //文件名
        $moveFile = $upload_path . $guid . '.' . $extension;

        if (!move_uploaded_file($_FILES['bigSearch_file']['tmp_name'], G_APPLICATION_BASEPATH . $moveFile)) {
            echo "<script>parent.E.loadding.close();parent.E.alert('系统错误，上传失败');</script>";
            return;
        }


        //读取文件
        $excelData = file(G_APPLICATION_BASEPATH . $moveFile);
        if (!isset($excelData[0])) {
            echo "<script>parent.E.loadding.close();parent.E.alert('导入数据为空');</script>";
            return;
        }

        /**
         * ======================================
         * 将会员名文件路径写入会员名文件路径表 start
         * ======================================
         */
        $fileName = basename( $moveFile );
        $file_path_obj = new entity( 'promotion_coupon_import_cust_file_path' );
        $file_path_obj->creator = $G_PGLOB->currentUserID;
        $file_path_obj->couponID = $_REQUEST['couponID'];
        $file_path_obj->cust_file_path = $fileName;
        $G_PGLOB->DBCA->save( $file_path_obj );

        die("<script>parent.coupon.bigImportMsg('导入成功,等待后台程序处理',0);</script>");
    }
    
    //add by 2014-10-29 yim.hu FUN-BK-0010 /优惠券重置显示页面 start

    public function resetCoupon(){
    	
    	
        global $G_PGLOB;

        $G_PGLOB->smarty->display('promotion/reset_coupon_list.tpl');
    }
    //add by 2014-10-29 yim.hu FUN-BK-0010 /优惠券重置显示页面 end
}